package sk.stuba.fiit.clientApp.gui.handler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JOptionPane;


import sk.stuba.fiit.clientApp.cvo.BasicPanelDataCVO;

import sk.stuba.fiit.clientApp.gui.model.FileTableModel;
import sk.stuba.fiit.clientApp.gui.panel.BasicPanel;
import sk.stuba.fiit.clientApp.singeltons.ControllerLocatorSingelton;
import sk.stuba.fiit.ltasys.ws.schema.beans.Xadestype;

/**
 * Trieda zodpovedná za vytvorenie podpisu --momentálne vytvára len časovú
 * pečiatku
 * 
 * @author Marek Hruška
 * 
 */
public class SignActionListener implements ActionListener {

	private static final int PATH_FILE = 3;

	private BasicPanel panel = null;

	public SignActionListener(BasicPanel basicPanel) {
		panel = basicPanel;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {

		if (!panel.validateRequiredFields()) {
			return;
		}

		BasicPanelDataCVO dataCVO = new BasicPanelDataCVO();
		dataCVO.setSignatureMethod((String) panel.getJcomboSignMethod()
				.getSelectedItem());
		dataCVO.setDigestMethod((String) panel.getJcomboHashMethod()
				.getSelectedItem());

		
		dataCVO.setCreateSignatureTime(panel.getChboxAllData().isSelected());
		dataCVO.setAllDataTimestampPath(panel.getTextFieldCert().getText());
		
		FileTableModel model = (FileTableModel) panel.getTable().getModel();
		List<File> files = new ArrayList<File>(model.getRowCount());
		for (int i = 0; i < model.getRowCount(); i++) {
			files.add(new File((String) model.getValueAt(i, PATH_FILE)));
		}
		dataCVO.setFiles(files);
		dataCVO.setKeyFormat(panel.getSelectedFormat());
		dataCVO.setKeyPassword(panel.getPasswordField().getText());
		dataCVO.setKeyPath(panel.getTextFieldPrivateKey().getText());
		dataCVO.setCertificatePath(panel.getTextFieldPrivateKey().getText());
		dataCVO.setOutputFile(panel.getTextFieldOutput().getText());

		ControllerLocatorSingelton application = ControllerLocatorSingelton
				.getInstance();
		panel.getConsole().append(
				new Date() + "\t\tCreating signature start:\n");
		try{
		Xadestype signature = application.getSignatureContreoller()
				.createXMLSignature(dataCVO);
		panel.getConsole().append(
				new Date() + "\t\tXML signature was created and store to: "
						+ dataCVO.getOutputFile() + "\n");
		panel.getConsole().append("\n");
		}catch(Exception e){
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "Signature was not created successfully","Error",JOptionPane.ERROR_MESSAGE);
			panel.getConsole().append(
					new Date() + "\t\tXML signature was not created");
			panel.getConsole().append("\n");
		}
	}

}
